package com.yutel.system.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.yutel.system.dao.IXsMenuDao;
import com.yutel.system.repository.SysMenu;

@SuppressWarnings("unchecked")
public class SysMenuDao extends JdbcDaoSupport implements IXsMenuDao {
	public List<SysMenu> list(String id) {
		String sql = "select * from sys_menu where pid=? order by sort";
		return getJdbcTemplate().query(sql,new Object[]{id}, new UserRowMapper());
	}
	public SysMenu view(String id) {
		String sql = "select * from sys_menu where id="+id;
		return (SysMenu)getJdbcTemplate().queryForObject(sql, new UserRowMapper());
	}
	public void add(SysMenu menu) {
		menu.setId(next()+1);
		String sql="insert into sys_menu(id,pid,name,type,url,remark,sort) values(?,?,?,?,?,?,?)";
		getJdbcTemplate().update(sql,new Object[]{
				menu.getId(),menu.getPid(),menu.getName(),menu.getType(),
				menu.getUrl(),menu.getRemark(),menu.getSort()
		});
	}
	public void edit(SysMenu menu) {
		String sql="update sys_menu set pid=?,name=?,type=?,url=?,remark=?,sort=? where id=?";
		getJdbcTemplate().update(sql,new Object[]{
				menu.getPid(),menu.getName(),menu.getType(),
				menu.getUrl(),menu.getRemark(),menu.getSort(),menu.getId()
		});
	}
	public void del(String id) {
		String sql = "delete from sys_menu where id="+id;
		getJdbcTemplate().update(sql);
	}
	private int next() {
		String sql="select max(id) from sys_menu";
		return getJdbcTemplate().queryForInt(sql);
	}
	private class UserRowMapper implements RowMapper {
		public Object mapRow(ResultSet rs, int index) throws SQLException {
			SysMenu menu = new SysMenu();
			menu.setId(rs.getInt("id"));
			menu.setPid(rs.getInt("pid"));
			menu.setName(rs.getString("name"));
			menu.setType(rs.getString("type"));
			menu.setUrl(rs.getString("url"));
			menu.setRemark(rs.getString("remark"));
			menu.setSort(rs.getInt("sort"));
			return menu;
		}
	}
}
